package com.polaris.live.ui.main.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.R
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.ext.formatNumberWithK
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.AppCodeUtils
import com.polaris.live.constant.UserRankConst
import com.polaris.live.databinding.FragmentDailyListBinding
import com.polaris.live.databinding.HeadMonthListBinding
import com.polaris.live.interface_bag.OnPartyGameSwitchListener
import com.polaris.live.resp.back_resp.PartyGameResp
import com.polaris.live.resp.bean.UserRankItemVo
import com.polaris.live.resp.bean.UserRankVo
import com.polaris.live.ui.main.adapter.MonthListAdapter
import com.polaris.live.viewmodel.login.UserRankViewModel
import com.polaris.live.widget.LevelChangeColorText
import com.polaris.live.widget.LevelView
import com.polaris.live.widget.VipLevelView
import com.polaris.live.widget.avatar.AvatarView
import com.polaris.live.widget.avatar.FrameImageUtils
import com.polaris.live.widget.country.CountryRoundView
import com.polaris.live.widget.refresh.EmptyView

/**
 * 月榜
 *
 * @author Created by lucas on 2023/10/30 17:16
 * @since 1.0.0
 */
class MonthListFragment : BaseVbFragment<UserRankViewModel, FragmentDailyListBinding>(),
    OnPartyGameSwitchListener {

    private var mType: Int = UserRankConst.TYPE_RICH
    private lateinit var mAdapter: MonthListAdapter

    private var mGameResp: PartyGameResp? = null

    private val emptyView by lazy { EmptyView(requireContext()) }

    override fun initView(savedInstanceState: Bundle?) {
        mType = arguments?.getInt("type") ?: UserRankConst.TYPE_RICH
        mGameResp = arguments?.getParcelable("gameResp")

        val userResp = UserManager.getUser()
        mBinding.avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(userResp.decoration?.avatarFrame))
        mBinding.ivUserHead.setImageUrl(userResp.avatar, userResp.userId)

        mBinding.tvUserName.text = userResp.nickname
        mBinding.tvUserName.setNicknameColor(
            userResp.decoration?.nicknameColor,
            R.color.color_b2ffffff
        )
        mBinding.tvCountry.setCountry(userResp.profile?.secondCountry)
        val sex = if (mGameResp != null) {
            UserManager.getUser().sex
        } else {
            when (mType) {
                UserRankConst.TYPE_CHARM -> AppConst.UserSex.WOMAN
                UserRankConst.TYPE_RICH -> AppConst.UserSex.MAN
                else -> UserManager.getUser().sex
            }
        }

        mBinding.tvLevel.setRichCharmBySexLevel(sex, userResp.account?.richs, userResp.account?.charms)
        mBinding.vipView.setVipLevel(userResp.profile?.vipLevel)
        mAdapter = MonthListAdapter(mType, mGameResp)

        mBinding.rvDailyList.adapter = mAdapter
        mBinding.rvDailyList.layoutManager = LinearLayoutManager(requireContext())
        val gameResp = mGameResp
        if (gameResp != null) {
            mViewModel.rankPartyGameMonthLiveData.observe(this) { resultState ->
                parseState(resultState, {
                    handleRankData(it)
                })
            }
            mViewModel.getPartyGameMonth(gameResp.id)
        } else {
            when (mType) {
                UserRankConst.TYPE_CHARM -> {//魅力榜
                    mViewModel.rankCharmMonthLiveData.observe(this) { state ->
                        parseState(state, {
                            handleRankData(it)
                        })
                    }
                    mViewModel.getCharmMonthRank()
                }

                UserRankConst.TYPE_RICH -> {//财富榜
                    mViewModel.rankRichMonthLiveData.observe(this) { state ->
                        parseState(state, {
                            handleRankData(it)
                        })
                    }
                    mViewModel.getRichMonthRank()
                }

                else -> {
                    mViewModel.rankGameMonthLiveData.observe(this) { state ->
                        parseState(state, {
                            handleRankData(it)
                        })
                    }
                    mViewModel.getGameMonthRank()
                }
            }
        }

        mViewModel.rankAnonymousLiveData.observe(this) {
            if (gameResp != null) {
                gameResp.id.let { it1 -> mViewModel.getPartyGameMonth(it1) }
            } else {
                when (mType) {
                    UserRankConst.TYPE_CHARM -> mViewModel.getCharmMonthRank()//魅力榜
                    UserRankConst.TYPE_RICH -> mViewModel.getRichMonthRank()//财富榜
                    else -> mViewModel.getGameMonthRank()
                }
            }
        }

        mBinding.switchBtn.setOnCheckedChangeListener { buttonView, isSelected ->
            mBinding.checkbox.isSelected = isSelected

            if (buttonView.isPressed) {
                val type = if (gameResp != null) {
                    mViewModel.getDayOrMonthType(gameResp, false)
                } else {
                    when (mType) {
                        UserRankConst.TYPE_CHARM -> UserRankConst.CHARM_MONTH
                        UserRankConst.TYPE_RICH -> UserRankConst.RICH_MONTH
                        else -> UserRankConst.GAME_MONTH
                    }
                }
                mViewModel.rankAnonymous(if (isSelected) 0 else 1, type)
            }
        }
    }

    private fun handleRankData(data: UserRankVo) {
        mBinding.tvNum.text = if (data.selfRank <= 100 && data.selfRank != 0) {
            data.selfRank.toString()
        } else if (data.selfRank > 100) {
            "100+"
        } else {
            "-"
        }
        mBinding.tvCoins.text = data.selfScore.toString()

        mBinding.checkbox.isSelected = data.anonymous == 0
        mBinding.switchBtn.isChecked = data.anonymous == 0

        if (mType != UserRankConst.TYPE_CHARM) {
            val drawable = context?.let { ContextCompat.getDrawable(it, R.drawable.icon_diamond) }
            mBinding.tvCoins.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null)
        }
        if (mGameResp != null) {
            mBinding.tvCoins.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
        }

        val users = data.users
        if (users.isEmpty()) {
            if (!mAdapter.hasHeaderLayout()) {
                emptyView.setEmptyTip(
                    R.drawable.img_weishangbang,
                    StringUtils.getString(com.polaris.live.translation.R.string.no_hava_data),
                    ColorUtils.getColor(R.color.color_ffffff_50),
                    128, 139
                )
                mAdapter.setEmptyView(emptyView)
            }
            return
        }

        HeadMonthListBinding.inflate(LayoutInflater.from(context), null, false).apply {

            if (AppCodeUtils.isAR()) {
                icList.setImageResource(R.drawable.img_dizuo)
            } else {
                icList.setImageResource(R.drawable.icon_dizuo)
            }

            val userVo1 = users.getOrNull(0)
            if (userVo1 != null) {
                handleUserData(
                    userVo1,
                    ivUserHeadOne,
                    tvUserNameOne,
                    tvCountryOne,
                    tvLevelOne,
                    tvScoreOne,
                    vipViewOne
                )
            }
            val userVo2 = users.getOrNull(1)
            if (userVo2 != null) {
                handleUserData(
                    userVo2,
                    ivUserHeadTwo,
                    tvUserNameTwo,
                    tvCountryTwo,
                    tvLevelTwo,
                    tvScoreTwo,
                    vipViewTwo
                )
            } else {
                ivUserHeadTwoBg.visibility = View.GONE
            }
            val userVo3 = users.getOrNull(2)
            if (userVo3 != null) {
                handleUserData(
                    userVo3,
                    ivUserHeadThree,
                    tvUserNameThree,
                    tvCountryThree,
                    tvLevelThree,
                    tvScoreThree,
                    vipViewThree
                )
            } else {
                ivUserHeadThreeBg.visibility = View.GONE
            }

            mAdapter.setHeaderView(root)
        }

        if (users.size > 3) {
            mAdapter.setList(data.users.subList(3, data.users.size))
        } else {
            mAdapter.setList(listOf())
        }
    }

    private fun handleUserData(
        userVo: UserRankItemVo,
        avatarView: AvatarView,
        nicknameView: LevelChangeColorText,
        countryView: CountryRoundView,
        levelView: LevelView,
        coinView: TextView,
        vipLevelView: VipLevelView,
    ) {
        avatarView.setImageUrl(userVo.user.avatar, userVo.user.userId)
        vipLevelView.setVipLevel(userVo.user.vipLevel)
        nicknameView.text = userVo.user.nickname
        nicknameView.setNicknameColor(
            userVo.user.nicknameColor,
            R.color.color_e5ffffff
        )
        countryView.setCountry(userVo.user.country)
        val sex = if (mGameResp != null) {
            UserManager.getUser().sex
        } else {
            when (mType) {
                UserRankConst.TYPE_CHARM -> AppConst.UserSex.WOMAN
                UserRankConst.TYPE_RICH -> AppConst.UserSex.MAN
                else -> UserManager.getUser().sex
            }
        }

        levelView.setRichCharmBySexLevel(
            sex,
            userVo.user.richs,
            userVo.user.charms
        )
        if (mType != UserRankConst.TYPE_CHARM) {
            val drawable = context?.let { ContextCompat.getDrawable(it, R.drawable.icon_diamond) }
            coinView.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null)
        }

        if (mGameResp != null) {
            coinView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
        }

        coinView.text = userVo.score.formatNumberWithK()
    }

    override fun onGameSwitchCallback(gameResp: PartyGameResp) {
        if (gameResp.id == mGameResp?.id) return
        mGameResp = gameResp
        mViewModel.getPartyGameMonth(gameResp.id)
    }
}